package com.mdinic.blogovi.ctrl;

import com.mdinic.blogovi.model.Email;
import com.mdinic.blogovi.model.EmailType;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/emails")
@Controller
@RooWebScaffold(path = "emails", formBackingObject = Email.class)
@RooWebFinder
public class EmailController {

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Email email, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, email);
            return "emails/create";
        }
        uiModel.asMap().clear();
        email.persist();
        return "redirect:/admin/emails/" + encodeUrlPathSegment(email.getId().toString(), httpServletRequest);
    }

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Email());
        return "emails/create";
    }

    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("email", Email.findEmail(id));
        uiModel.addAttribute("itemId", id);
        return "emails/show";
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("emails", Email.findEmailEntries(firstResult, sizeNo));
            float nrOfPages = (float) Email.countEmails() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("emails", Email.findAllEmails());
        }
        return "emails/list";
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Email email, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, email);
            return "emails/update";
        }
        uiModel.asMap().clear();
        email.merge();
        return "redirect:/admin/emails/" + encodeUrlPathSegment(email.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, Email.findEmail(id));
        return "emails/update";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Email email = Email.findEmail(id);
        email.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/admin/emails";
    }

    @RequestMapping(params = { "find=ByActiveNot", "form" }, method = RequestMethod.GET)
    public String findEmailsByActiveNotForm(Model uiModel) {
        return "emails/findEmailsByActiveNot";
    }

    @RequestMapping(params = "find=ByActiveNot", method = RequestMethod.GET)
    public String findEmailsByActiveNot(@RequestParam(value = "active", required = false) Boolean active, Model uiModel) {
        uiModel.addAttribute("emails", Email.findEmailsByActiveNot(active == null ? Boolean.FALSE : active).getResultList());
        return "emails/list";
    }

    @RequestMapping(params = { "find=ByType", "form" }, method = RequestMethod.GET)
    public String findEmailsByTypeForm(Model uiModel) {
        uiModel.addAttribute("emailtypes", java.util.Arrays.asList(EmailType.class.getEnumConstants()));
        return "emails/findEmailsByType";
    }

    @RequestMapping(params = "find=ByType", method = RequestMethod.GET)
    public String findEmailsByType(@RequestParam("type") EmailType type, Model uiModel) {
        uiModel.addAttribute("emails", Email.findEmailsByType(type).getResultList());
        return "emails/list";
    }

    void populateEditForm(Model uiModel, Email email) {
        uiModel.addAttribute("email", email);
        uiModel.addAttribute("emailtypes", Arrays.asList(EmailType.values()));
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
        }
        return pathSegment;
    }
}
